import 'package:animated_flip_counter/animated_flip_counter.dart';
import 'package:eh_mobile/common/utils/index.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/light_card_overlay.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../../common/models/light_card.dart';
import 'dart:io';

import '../../homepage/model/home_device_model.dart';

// 恒温列表卡片
class TempCardItem extends StatefulWidget {
  const TempCardItem(this.lightCardModel,
      {super.key,
      this.editOpen = false,
      this.lightCardEditCallback,
      this.renameCallback,
      this.cardEventCallback,
      this.cardTapCallback});
  final HomeDeviceModelDevices lightCardModel;
  final bool editOpen; // 开启编辑
  // 编辑返回
  final ValueChanged<bool>? lightCardEditCallback;
  // 重命名返回
  final ValueChanged<String>? renameCallback;
  //卡片点击跳转
  final VoidCallback? cardTapCallback;
  // 卡片开关控制
  final ValueChanged<bool>? cardEventCallback;

  @override
  State<TempCardItem> createState() {
    return _TempCardItemState();
  }
}

class _TempCardItemState extends State<TempCardItem> {
  // final SmartHomeInfoController _controller = Get.find();
  // double _currectTempValue = 0.5;
  late HomeDeviceModelDevices _lightCardModel;
  late GlobalKey _anchorKey;
  late double _tempValue;

  final double _maxValue = 32.0;
  final double _minValue = 16.0;

  double _superHeight = 0;
  late bool _cardOpen = widget.lightCardModel.cardOpen!;
  @override
  void initState() {
    _anchorKey = GlobalKey(debugLabel: widget.lightCardModel.name);
    _lightCardModel = widget.lightCardModel;
    if (widget.lightCardModel.online == false) {
      widget.lightCardModel.hasEvent = false;
    }
    _tempValue = widget.lightCardModel.tempValue!;
    super.initState();
  }

  @override
  void didUpdateWidget(covariant TempCardItem oldWidget) {
    _lightCardModel = widget.lightCardModel;
    _tempValue = widget.lightCardModel.tempValue!;
    _cardOpen = widget.lightCardModel.cardOpen!;
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return _buildView(context);
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (_superHeight > 0) {
          if (constraints.biggest.height >= _superHeight) {
            _cardOpen = true;
          } else {
            _cardOpen = false;
          }
        }

        _superHeight = constraints.biggest.height;

        return widget.editOpen
            ? _buildMainWidget()
            : GestureDetector(
                onLongPress: () {
                  HapticFeedback.mediumImpact();
                  LightCardOverlay.show(
                    context,
                    offset: _anchorKey.position()!,
                    size: _anchorKey.size!,
                    deviceLListType: DeviceLListType.temp,
                    lightCardModel: widget.lightCardModel,
                    lightCardOverlayCallback: (
                        {bool? isEdit, bool? isRename, name}) {
                      if (isEdit!) {
                        widget.lightCardEditCallback!(true);
                      } else if (isRename!) {
                        setState(() {
                          widget.lightCardModel.name = name;
                        });
                        widget.renameCallback!(name!);
                      }
                    },
                  );
                },
                child: _buildMainWidget());
      },
    );
  }

// 创建主要视图
  Widget _buildMainWidget() {
    return SizedBox(
      key: _anchorKey,
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                color: widget.lightCardModel.hasEvent!
                    ? const Color.fromRGBO(196, 196, 196, 1)
                    : const Color.fromRGBO(55, 55, 55, 1),
                borderRadius: BorderRadius.circular(25.r)),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(8, 8, 0, 0).r,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 50.w,
                  height: 50.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(25).w,
                    color: widget.lightCardModel.hasEvent!
                        ? const Color.fromRGBO(50, 50, 50, 1)
                        : const Color.fromRGBO(38, 38, 38, 1),
                  ),
                  child: IconButton(
                    onPressed: () {
                      if (widget.editOpen || !widget.lightCardModel.online!) {
                        return;
                      }
                      setState(() {
                        widget.lightCardModel.hasEvent =
                            !widget.lightCardModel.hasEvent!;
                      });

                      widget
                          .cardEventCallback!(widget.lightCardModel.hasEvent!);
                    },
                    iconSize: 28.r,
                    icon:Image.asset(
                      'assets/images/ic_aircon_off.png',
                      color: widget.lightCardModel.hasEvent!
                          ? const Color.fromRGBO(222, 222, 222, 1)
                          : const Color.fromRGBO(255, 255, 255, 0.25),
                    ),
                  ),
                ),
                8.sizedBoxWidth,
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [_buildLightNameText(), _buildLightStateText()],
                  ),
                )
              ],
            ),
          ),
          Positioned(
            top: carHeight*0.77 - 60.r,
            left: 8.r,
            child: SizedBox(
              height: 50.r,
              width: carHeight - 16.r,
              child: _buildTempChangeWidget().userInterface(!widget.editOpen ||
                  !widget.lightCardModel.hasEvent! ||
                  widget.lightCardModel.online!),
            ),
          ),
          Positioned(
            top: 0,
            left: 60.r,
            child: Container(
              height: carHeight*0.5 / 2.0,
              width: carHeight - 60.r,
              decoration: BoxDecoration(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(25.r)),
            ).onClick(() {
              if (widget.lightCardModel.online == false || widget.editOpen) {
                return;
              }
              if (widget.cardTapCallback != null) {
                widget.cardTapCallback!();
              }
            }),
          ),
        ],
      ),
    );
  }

  // 创建名称文字
  Widget _buildLightNameText() {
    Color textColor = widget.lightCardModel.hasEvent!
        ? const Color.fromRGBO(50, 50, 50, 1)
        : const Color.fromRGBO(255, 255, 255, 0.5);
    if (widget.lightCardModel.online == false) {
      textColor = const Color.fromRGBO(255, 255, 255, 0.2);
    }

    return Container(
      padding: EdgeInsets.only(top: 1, right: widget.editOpen ? 20 : 4).r,
      height: 21.w,
      // width: 44,
      child: Text(
        widget.lightCardModel.name!,
        textAlign: TextAlign.left,
        overflow: TextOverflow.ellipsis,
        softWrap: true,
        maxLines: 1,
        style: 16.ts.copyWith(color: textColor,fontWeight:Platform.isAndroid? FontWeight.w500:FontWeight.w600),
      ),
    );
  }

  // 创建灯光状态文字
  Widget _buildLightStateText() {
    String stateText = widget.lightCardModel.hasEvent!
        ? '制冷 - ${widget.lightCardModel.currentTempValue}°'
        : '关闭 - ${widget.lightCardModel.currentTempValue}°';
    Color textColor = widget.lightCardModel.hasEvent!
        ? const Color(0XFF323232)
        : const Color.fromRGBO(255, 255, 255, 0.38);

    Color backgroundColor = Colors.transparent;
    if (widget.lightCardModel.online == false) {
      stateText = ' 不可用 ';
      textColor = const Color.fromRGBO(255, 138, 100, 1);
      backgroundColor = const Color.fromRGBO(255, 138, 100, 0.25);
    }
    return Container(
        margin: const EdgeInsets.only(top: 5).r,
        height: 18.r,
        decoration: BoxDecoration(
            color: backgroundColor, borderRadius: BorderRadius.circular(7)),
        child: Text(
          overflow: TextOverflow.ellipsis,
          softWrap: false,
          maxLines: 1,
          stateText,
          style: 14.ts.copyWith(color: textColor),
        ));
  }

  // 创建温度调节按钮
  Widget _buildTempChangeWidget() {
    Color bgColor = widget.lightCardModel.hasEvent!
        ? const Color.fromRGBO(255, 255, 255, 1)
        : const Color.fromRGBO(38, 38, 38, 1);
    Color iconColor = widget.lightCardModel.hasEvent!
        ? const Color.fromRGBO(50, 50, 50, 1)
        : const Color.fromRGBO(55, 55, 55, 1);
    Color textColor = widget.lightCardModel.hasEvent!
        ? const Color.fromRGBO(50, 50, 50, 1)
        : const Color.fromRGBO(255, 255, 255, 0.5);
    return AnimatedOpacity(
      opacity: _cardOpen ? 1 : 0,
      curve: _cardOpen ? Curves.easeInCirc : Curves.easeOutExpo,
      duration: const Duration(milliseconds: 300),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
              alignment: Alignment.center,
            width: 50.r,
            height: 50.r,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(17).r,
                color: _tempValue > _minValue
                    ? bgColor
                    : const Color.fromRGBO(255, 255, 255, 0.35)),
            child: Image.asset('assets/images/list_ic_down.png'),
          ).onClick(() {
            if (_tempValue > _minValue) {
              setState(() {
                _tempValue -= 0.1;
                if (_tempValue < _minValue) {
                  _tempValue = _minValue;
                }
                widget.lightCardModel.tempValue = _tempValue;
              });
            }
          }),
          AnimatedFlipCounter(
            value: _tempValue,
            fractionDigits: 1, // 小数点位数
            textStyle: TextStyle(
              fontSize: 18.sp,
              color: textColor,
              fontWeight: FontWeight.w600
            ),
          ),
          Container(
              // padding: EdgeInsets.all(11.r),
            alignment: Alignment.center,
              width: 50.r,
              height: 50.r,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(17).r,
                  color: _tempValue < _maxValue
                      ? bgColor
                      : const Color.fromRGBO(255, 255, 255, 0.35)),
              child: Image.asset('assets/images/list_ic_up.png'),
            ).onClick(
            () {
              if (_tempValue < _maxValue) {
                setState(() {
                  _tempValue += 0.1;
                  if (_tempValue > _maxValue) {
                    _tempValue = _maxValue;
                  }
                  widget.lightCardModel.tempValue = _tempValue;
                });
              }
            },
          )
        ],
      ),
    );
  }

  //卡片宽高
  double get carHeight{
    return (1.sw - 24.r - 10.r) / 2.0;
  }
}
